package com.jiulong.controller;



import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



import javax.servlet.http.HttpSession;

import org.jdom.JDOMException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.fastjson.JSONObject;
import com.jiulong.common.utils.PayCommonUtil;
import com.jiulong.common.utils.PayConfigUtil;
import com.jiulong.common.utils.XMLUtil;
import com.jiulong.dao.TFavoriteMapper;
import com.jiulong.dao.TGiftMapper;
import com.jiulong.dao.TOrderMapper;
import com.jiulong.dao.TProductMapper;
import com.jiulong.model.TAccount;
import com.jiulong.model.TFavorite;
import com.jiulong.model.TGift;
import com.jiulong.model.TOrder;
import com.jiulong.model.TProduct;
import com.jiulong.service.AccountService;
import com.jiulong.service.OrderService;


@Controller
public class xkControl extends BaseController{

	@Autowired
	AccountService accountService;
	@Autowired
	TProductMapper tProductMapper;
	@Autowired
	TOrderMapper tOrderMapper;
	@Autowired
	TGiftMapper tGiftMapper;
	@Autowired
	TFavoriteMapper tFavoriteMapper;
	@RequestMapping("/order")
	public String order(HttpServletRequest request,HttpServletResponse response,Model model) throws IOException{
		//String openid="ohx_wwiIXSM7yFNDcaLymiMeIh9o";
			HttpSession session = request.getSession();
		String openid=session.getAttribute("openid").toString();
		TAccount tAccount=	accountService.findAccountbyId(openid);
		System.out.println("我通过openid找到了用户的昵称！"+tAccount.getAccount());
		String account=tAccount.getAccount();
		String score=tAccount.getScore().toString();
		String rank=tAccount.getRank();
		model.addAttribute("rank", rank);
		model.addAttribute("score", score);
		model.addAttribute("account", account);	
		
		String productId= session.getAttribute("productId").toString();
		//String productId="10008";
		TProduct product =new TProduct();
		product= tProductMapper.selectByPrimaryKey(Integer.parseInt(productId));
		String productName=product.getName();
		String productIntroduce=product.getIntroduce();
		String imageUrl1=product.getPicture();
		String imageUrl="http://threeshop1.oss-cn-hangzhou.aliyuncs.com"+imageUrl1;
		model.addAttribute("productName", productName);
		model.addAttribute("productIntroduce", productIntroduce);
		model.addAttribute("account", account);	
		model.addAttribute("imageUrl", imageUrl);
		TOrder order=accountService.findOrderbyId(account);
		String amount=order.getAmount().toString();
	
		model.addAttribute("amount", amount);		
		return "order";
	}
	
	
	@RequestMapping("/huitiao")
	public String huitiao(HttpServletRequest request,HttpServletResponse response) throws IOException{
		System.out.println("我是回调的参数！");
		//读取参数
		InputStream inputStream ;
		StringBuffer sb = new StringBuffer();
		inputStream = request.getInputStream();
		String s ;
		BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
		while ((s = in.readLine()) != null){
			sb.append(s);
		}
		in.close();
		inputStream.close();

		//解析xml成map
		Map<String, String> m = new HashMap<String, String>();
		try {
			m = XMLUtil.doXMLParse(sb.toString());
		} catch (JDOMException e) {
			System.out.println("解析失败！");
			e.printStackTrace();
		}
		
		//过滤空 设置 TreeMap
		SortedMap<Object,Object> packageParams = new TreeMap<Object,Object>();		
		Iterator it = m.keySet().iterator();
		while (it.hasNext()) {
			String parameter = (String) it.next();
			String parameterValue = m.get(parameter);
			
			String v = "";
			if(null != parameterValue) {
				v = parameterValue.trim();
			}
			packageParams.put(parameter, v);
		}
		
		// 账号信息
        String key = PayConfigUtil.getKey(); // key
        String out_trade_no = (String)packageParams.get("out_trade_no");
        //logger.info(packageParams);
	    //判断签名是否正确
	    if(PayCommonUtil.isTenpaySign("UTF-8", packageParams,key)) {
	        //------------------------------
	        //处理业务开始
	        //------------------------------
	        String resXml = "";
	        if("SUCCESS".equals((String)packageParams.get("result_code"))){
	        	// 这里是支付成功

	        	String mch_id = (String)packageParams.get("mch_id");
	        	String openid = (String)packageParams.get("openid");
	        	String is_subscribe = (String)packageParams.get("is_subscribe");
	        	
	        	String bank_type = (String)packageParams.get("bank_type");
	        	String total_fee = (String)packageParams.get("total_fee");
	        	String transaction_id = (String)packageParams.get("transaction_id");    	
	        	System.out.println("mch_id:"+mch_id);
	        	System.out.println("openid:"+openid);
	        	System.out.println("is_subscribe:"+is_subscribe);
	        	System.out.println("out_trade_no:"+out_trade_no);
	        	System.out.println("total_fee:"+total_fee);
	        	System.out.println("bank_type:"+bank_type);
	        	
	        	//成功回调后需要处理预生成订单的状态和一些支付信息	
	        	//正常处理相关业务逻辑  
	        	//查询数据库中订单，首先判定订单中金额与返回的金额是否相等，不等金额被纂改  
	        	System.out.println("通过订单号开始查找");
	        	TOrder order=accountService.findOrderbytrade(out_trade_no);
	        	//String amount=order.getAmount().toString();
	        	//比较返回的金额
	        	// String total_fee1=String.valueOf((Double.valueOf(amount)*100));
	    	   //  String total_fee2 = total_fee1.substring(0,total_fee1.indexOf("."));
/*	    	     if(!total_fee2.equals(total_fee)){
	    	    	 System.out.println("金额被篡改，请联系技术人员！");
	    	    	 return "error";
	    	     }  */ 	
	    	     String payStatus=order.getPaystatus();
	    	     if(payStatus.equals("y")){
	    	    	 System.out.println("订单已被支付！");
	    	    	 return "error";
	    	     }
	    	     order.setPaystatus("y");
	    	     tOrderMapper.updateByPrimaryKeySelective(order);
	    	     System.out.println("更改后订单的状态是："+order.getPaystatus());
	         
	    	     try{
	    	    	    	 
	    	 		List favorite=accountService.findFavoritebytrade(out_trade_no);
	    	 		if(favorite.toString()!="[]"){
	    	 			 int gift_id=Integer.parseInt(((TFavorite) favorite.get(0)).getProductid());
		    	 	     tGiftMapper.deleteByPrimaryKey(gift_id);
		    	 	     System.out.println("删除了已使用的优惠券！  "+gift_id);
	    	 		}   
	    	 	}catch(Exception e){
	    	 		e.printStackTrace();
	    	 	}
	     System.out.println("删除已使用的优惠券有没哟偶被删除");
	    	   //判定订单是否已经被支付，不可重复支付 
	        	//优惠券数量减一
	        	System.out.println("transaction_id:"+transaction_id);	
	        	  resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
		                    + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
	        	
	        	
	        } else {
	        	System.out.println("支付失败,错误信息：" + packageParams.get("err_code")+
	        			            "-----订单号：：："+out_trade_no+"*******支付失败时间：：：："
	        			+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
	        	
	        	String err_code = (String)packageParams.get("err_code");

		            resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
		                    + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
       
	        }
	        //------------------------------
	        //处理业务完毕
	        //------------------------------
	        BufferedOutputStream out = new BufferedOutputStream(
	                response.getOutputStream());
	        out.write(resXml.getBytes());
	        out.flush();
	        out.close();
	    } else{
	    	System.out.println("通知签名验证失败---时间::::"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
	    }
		return "index";
	}
	//从我的订单里面重新生成订单
	
	@RequestMapping(value="/checkChuanZhi" ,method=RequestMethod.POST)
	public String checkChuanZhi(HttpServletRequest request,HttpServletResponse response,Model model) throws IOException{

		String orderId=request.getParameter("orderId");
		if(orderId==null){
			return "error3";
		}
		System.out.println("我拿到了订单的id");
		String giftId1=request.getParameter("giftId");

		String giftprice=null;
		TGift gi=new TGift();
		if(giftId1!=null){
			try{
				int giftId=Integer.parseInt(giftId1);
			 gi=tGiftMapper.selectByPrimaryKey(giftId);
			  giftprice= String.valueOf(gi.getGiftprice())  ;
			 }catch(Exception e){
				 e.printStackTrace();
			 }
			
		}
	
		System.out.println("我拿到了折扣券的优惠");
		HttpSession session = request.getSession();
		//String openid="ohx_wwiIXSM7yFNDcaLymiMeIh8o";
		String openid=	session.getAttribute("openid").toString();
		System.out.println("我拿到了openid");
		TOrder order=new TOrder();
		   //生成订单号
					long currentTimeMillis = System.currentTimeMillis();
				    String strReq =  currentTimeMillis + "jiulongWei";
				    String out_trade_no = strReq; 
		order=tOrderMapper.selectByPrimaryKey(Integer.parseInt(orderId));
		String amount2=order.getAmount().toString();
		//修改订单的订单号
		 order.setRemark(out_trade_no);
	     tOrderMapper.updateByPrimaryKeySelective(order);
		double a;
		if(giftprice!=null){
		
			a=	Double.parseDouble(amount2)-Double.parseDouble(giftprice);
			a=Math.round(a*100)/100.00;
		}else{
			a=Double.parseDouble(amount2);
		}
		String amount1=String.valueOf(a);
	
	
				
		String total_fee1=String.valueOf((Double.valueOf(amount1)*100));
	     String total_fee = total_fee1.substring(0,total_fee1.indexOf("."));
	     System.out.println("我拿到了最终的生成价格的价格");
	
		String js = null;
		try {
			js = weixin_pay.weixin_pay(openid,total_fee,out_trade_no);
		} catch (Exception e) {
			System.out.println("预支付生成订单出错！");
			e.printStackTrace();
		}
		JSONObject jo=JSONObject.parseObject(js);
		model.addAttribute("appId", jo.get("appId"));
		model.addAttribute("timeStamp", jo.get("timeStamp"));
		model.addAttribute("nonceStr", jo.get("nonceStr"));
		model.addAttribute("package", jo.get("package"));
	    //model.addAttribute("packageValue", jo.get("packageValue"));    //这里用packageValue是预防package是关键字在js获取值出错
	    model.addAttribute("paySign", jo.get("paySign"));   
	    TAccount tAccount=	accountService.findAccountbyId(openid);
		String score=tAccount.getScore().toString();
		String rank=tAccount.getRank();
		String nickname=tAccount.getNickname();
		String imageUrl=order.getExpressno();
		String productName=order.getExpresscode();
		String productIntroduce=order.getExpressname();
		model.addAttribute("rank", rank);
		model.addAttribute("score", score);
		model.addAttribute("account", nickname);	
		model.addAttribute("productName", productName);
		model.addAttribute("productIntroduce", productIntroduce);
		model.addAttribute("price", amount1);	
		model.addAttribute("imageUrl", imageUrl);
		System.out.println("神兽保佑，图片地址快快出来"+imageUrl);
		//植入销券记录
		
		if(giftId1!=null){
		try{
			TFavorite favorite=new TFavorite();
			favorite.setProductid(giftId1);
			favorite.setAccount(out_trade_no);
			tFavoriteMapper.insert(favorite);
		}catch(Exception e){
			e.printStackTrace();
		}
		}

		return "grzx";
	}
	@RequestMapping("/yhhd")
	public String kfyd1(HttpServletRequest request,HttpServletResponse response) throws IOException{
		
		return "yhhd";
	}
	
	
	@Autowired
	OrderService orderService;
	@RequestMapping("/selectOrder")
	public String selectOrder(HttpServletRequest request,HttpServletResponse response,Model model) throws IOException{
		HttpSession session = request.getSession();
		String account=	session.getAttribute("account").toString();
		//String account="_out_1395897863364";
		String openid=	session.getAttribute("openid").toString();
		//String openid="ohx_wwmIaxOreZYa-RH8si7tVqYs";
		  TAccount tAccount=	accountService.findAccountbyId(openid);
			String score=tAccount.getScore().toString();
			String rank=tAccount.getRank();
			String nickname=tAccount.getNickname();
			model.addAttribute("rank", rank);
			model.addAttribute("score", score);
			model.addAttribute("account", nickname);
			List gift=orderService.findGiftbyId(nickname);
			List list=orderService.findOrderDetailByOpenid(nickname);
		 model.addAttribute("detailList", list);
		 model.addAttribute("detailGift", gift);
	System.out.println();
		return "grzxDing";
	}
}
